package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.BigDateBean;
import com.zhongkai.Bean.BigUnitBean;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.StringStatic;
import com.zhongkai.app.service.BigInTimeService;
import com.zhongkai.app.service.DeviceOperationService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Anomaly;
import com.zhongkai.model3.SetUnit;
import com.zhongkai.model3.Unlike;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;


@Service
@Transactional(rollbackFor = Exception.class)
public class BigInTimeServiceImpl implements BigInTimeService {

    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;


/*    @Autowired
    private JmsTemplate jmsTemplate;*/

    @Autowired
    private JedisClient jedisClient;

/*    @Autowired
    private RedisUtils redisUtils;*/


    @Autowired
    private DeviceOperationService deviceOperationService;


    /**
     * 获取单台设备的实时数据
     */
    @Override
    public ZhongkaiResult getUserInTime(String unit_uuid) throws IOException {

        if (StringUtils.isNullOrEmpty(unit_uuid)) {

            return ZhongkaiResult.build(400, "数据不完整");
        }


        String json = null; //查询缓存
        try {
            json = (String) jedisClient.get(StringStatic.REDIS_UNIT + unit_uuid);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }

        if (!StringUtils.isNullOrEmpty(json)) {


            ObjectMapper mapper = new ObjectMapper();

            BigUnitBean bigUnitBean = mapper.readValue(json, BigUnitBean.class);


            return ZhongkaiResult.ok(bigUnitBean);

        } else {
            deviceOperationService.deviceDown2(unit_uuid); //设备下线
            return ZhongkaiResult.build(400, "设备断开连接.....");
        }

    }


    /**
     * 设备异常记录
     *
     * @param unit_uuid 设备uuid
     * @param page      当前页数
     * @param rows      每页数据条数
     */
    @Override
    public ZhongkaiResult getUserRecord(String unit_uuid, Integer page, Integer rows) throws Exception {

        if (StringUtils.isNullOrEmpty(unit_uuid) || page == 0 || rows == 0) {

            return ZhongkaiResult.build(400, "数据不完整");
        }

        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Unlike.class);
        detachedCriteria.add(Restrictions.eq("unitUuid", unit_uuid)); //增加条件
        detachedCriteria.addOrder(Order.desc("solveTime")); //根据传入的字段进行降序排序
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);

        List<Unlike> rows1 = pageBean.getRows();
        List<String> list = new ArrayList<>();

        String strDate;
        DateTime dateTime = new DateTime();
        for (Unlike unlike : rows1) {
            //  unlike.getUnitUuid()
            //unitUuid
            strDate = "设备, " + dateTime.withMillis(unlike.getSolveTime()).toString("yyyy-MM-dd HH:mm:ss") + " "
                    + unlike.getWarCause() + "  错误代码: " + unlike.getWarCode();

            list.add(strDate);
        }

        pageBean.setRows(list);

        return ZhongkaiResult.ok(pageBean);

    }


    @Override
    public ZhongkaiResult getCurrent(String unit_uuid) throws Exception {


        Anomaly anomaly = (Anomaly) iBaseDao.get("from Anomaly se where se.setCard='" + unit_uuid + "'");
        if (anomaly != null){
            return ZhongkaiResult.ok(anomaly.getWarCause() + "@" + anomaly.getAnoTime());
        }else {
            return ZhongkaiResult.build(2001, "设备未报警");
        }
/*
        if (StringUtils.isNullOrEmpty(unit_uuid)) {

            return ZhongkaiResult.build(400, "数据不完整");
        }




        Object o = iBaseDao.get("select warning from SetUnit su where su.setUuid='" + unit_uuid + "' and su.setRemove='1'");//异常设备数量 warning是否报警  0正常 1报警

        if (o == null) {
            return ZhongkaiResult.build(400, "设备不存在");
        }

        if ("1".equals(o.toString())) {
            Anomaly anomaly = (Anomaly) iBaseDao.get("from Anomaly se where se.setCard='" + unit_uuid + "'");
            if (anomaly != null){
                return ZhongkaiResult.ok(anomaly.getWarCause() + "@" + anomaly.getAnoTime());
            }else {
                return ZhongkaiResult.build(2001, "设备未报警");
            }

        } else {
            return ZhongkaiResult.build(2001, "设备未报警");
        }*/


    }


    /**
     * 获取设备列表
     *
     * @param page   当前页数
     * @param rows   每页数据条数
     * @param status 类型 1 正常设备 2异常设备 3全部设备 4维修设备
     */
    @Override
    public ZhongkaiResult getUserAll(Integer page, Integer rows, Integer status) throws Exception {

        if (page == 0 || rows == 0 || status == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        PageBean pageBean = new PageBean();
        DetachedCriteria detachedCriteria;

        Collection collection = new ArrayList();

        ((ArrayList) collection).add(100);

        if (status == 1) {
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);


            detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
            detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主  1 未绑定 2 已绑定
            detachedCriteria.add(Restrictions.not(Restrictions.in("setStatus", collection))); //增加条件 不等于100  1 - 6 开机 0关机 100离线
            detachedCriteria.add(Restrictions.eq("warning", 0)); //增加条件 是否报警  0正常 1报警

            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
        } else if (status == 2) {
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);


            detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
            detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主  1 未绑定 2 已绑定
            detachedCriteria.add(Restrictions.not(Restrictions.in("setStatus", collection))); //增加条件 不等于100  1 - 6 开机 0关机 100离线
            detachedCriteria.add(Restrictions.eq("warning", 1)); //增加条件 是否报警  0正常 1报警


            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
        } else if (status == 4) {
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);


            detachedCriteria = DetachedCriteria.forClass(Anomaly.class);
            detachedCriteria.add(Restrictions.eq("orders", "1")); //已派单设备

            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);


            List<Anomaly> anomalies = pageBean.getRows();
            List<SetUnit> setUnits = new ArrayList<>();
            for (Anomaly anomaly : anomalies) {
                SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + anomaly.getSetCard() + "'");

                setUnits.add(setUnit);
            }

            pageBean.setRows(setUnits);
            //detachedCriteria.add(Restrictions.eq("warning", 2)); //增加条件 是否报警  1 否 2 是
        } else if (status == 3) {

            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);


            detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
            detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主  1 未绑定 2 已绑定
            //detachedCriteria.add(Restrictions.not(Restrictions.in("setStatus", collection))); //增加条件 不等于100  1 - 6 开机 0关机 100离线

            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
        } else {
            return ZhongkaiResult.build(500, "参数不合法");
        }


        List<SetUnit> rows1 = pageBean.getRows();
        //  System.out.println(pageBean.getRows().size());
        List<BigDateBean> bigDateBeans = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        BigUnitBean bigUnitBean; //设备实时数据对象

        //     System.out.println(rows1.size());
        String uuid;
        for (SetUnit setUnit : rows1) {

            if (setUnit == null) {
                pageBean.setRows(bigDateBeans);
                return ZhongkaiResult.ok(pageBean);
            }
            BigDateBean bigDateBean = new BigDateBean();

            uuid = setUnit.getSetUuid();
            String json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid); //查询缓存


            if (!StringUtils.isNullOrEmpty(json)) {


                bigUnitBean = mapper.readValue(json, BigUnitBean.class);


                //  System.out.println(b+"6666666");


                bigDateBean.setState(String.valueOf(setUnit.getSetStatus()));//设备状态 从redis中获取
                bigDateBean.setUser_name(setUnit.getUserName());//用户姓名 设备表中获取

                bigDateBean.setUnit_ip(setUnit.getSetIp());//设备ip地址 设备表中获取

                bigDateBean.setSignal(bigUnitBean.getSignal());//信号强度 从redis中获取

                bigDateBean.setPower(bigUnitBean.getPower()); //实时电压

                bigDateBean.setForce(bigUnitBean.getForce()); //实时电量

                bigDateBean.setPower_all(bigUnitBean.getPower_all());//总耗电量 设备表中获取

                bigDateBean.setUser_t(bigUnitBean.getUser_t());//设备设定温度 从redis中获取

                bigDateBean.setAddress_all(setUnit.getAppAddressAll());//设备完整地址 设备表中获取

                bigDateBean.setUnit_uuid(uuid);//设备uuid  设备表中获取

                bigDateBean.setWarning(bigUnitBean.getWarning()); //是否报警

                bigDateBean.setTrusteeship(setUnit.getTrusteeship()); //是否托管

                bigDateBean.setRepair(String.valueOf(setUnit.getRepair())); //是否维修

                bigDateBean.setUser_uuid(setUnit.getUserUuid());

                bigDateBean.setSetAlias(setUnit.getSetAlias());
            } else {

                // deviceOperationService.deviceDown2(uuid); //设备下线

                bigDateBean.setState("100");
                bigDateBean.setUser_name(setUnit.getUserName());//用户姓名 设备表中获取

                bigDateBean.setUnit_ip(setUnit.getSetIp());//设备ip地址 设备表中获取

                bigDateBean.setPower_all(setUnit.getBattery().toString());//总耗电量 设备表中获取

                bigDateBean.setAddress_all(setUnit.getAppAddressAll());//设备完整地址 设备表中获取

                bigDateBean.setUnit_uuid(uuid);//设备uuid  设备表中获取

                bigDateBean.setWarning(String.valueOf(setUnit.getWarning()));

                bigDateBean.setTrusteeship(setUnit.getTrusteeship()); //是否托管

                bigDateBean.setRepair(String.valueOf(setUnit.getRepair())); //是否维修
                bigDateBean.setUser_uuid(setUnit.getUserUuid());
                bigDateBean.setSetAlias(setUnit.getSetAlias());
            }


            bigDateBeans.add(bigDateBean);

            bigDateBean = null;

        }


        pageBean.setRows(bigDateBeans);
        return ZhongkaiResult.ok(pageBean);

    }


    /**
     * 获取所有设备统计
     */
    @Override
    public ZhongkaiResult getUnitCount() throws Exception {
        //1 统计所有已绑定用户的设备数量  and su.setBound='2'
        Long aLong = (Long) iBaseDao.get("select count(su) from SetUnit su where su.setRemove='1'");//未被删除的设备数量
        //2 统计正常设备数据 统计异常设备数据  统计维修设备数量
        Long normal = (Long) iBaseDao.get("select count(su) from SetUnit su where su.warning=0 and su.setRemove='1'");//正常设备数量 warning是否报警  0正常 1报警

        Long anomaly = (Long) iBaseDao.get("select count(su) from SetUnit su where su.warning=1 and su.setRemove='1'");//异常设备数量 warning是否报警  0正常 1报警


        Long wex = (Long) iBaseDao.get("select count(su) from Anomaly su where su.orders='1'");//统计维修设备数量


        Map<String, String> map = new HashMap<>();
        String res = "全部设备 " + aLong + "台/ " + "正常设备 " + normal + "台/ " + "异常设备 " + anomaly + " 台/ " + "维修设备 " + wex + "台";

        map.put("unit_all", String.valueOf(aLong));
        map.put("res", res);


        return ZhongkaiResult.ok(map);
    }


    /**
     * 根据用户uuid获取用户下全部设备
     *
     * @param user_uuid 用户uuid
     */
    @Override
    public ZhongkaiResult getUserUnitSum(String user_uuid) throws Exception {
        if (StringUtils.isNullOrEmpty(user_uuid)) {

            return ZhongkaiResult.build(400, "数据不完整");
        }

        List<SetUnit> list;
        //  List<FsonUser> fsonUsers  = iBaseDao.find("from FsonUser su where su.fUid='"+user_uuid+"'") fUid;
        list = iBaseDao.find("from SetUnit se where se.userUuid='" + user_uuid + "'");


        return ZhongkaiResult.ok(list);
    }


    /**
     * 设备用户名模糊查询
     *
     * @param user_name 模糊的用户姓名
     */
    @Override
    public ZhongkaiResult likeName(String user_name, Integer page, Integer rows) throws Exception {

        if (StringUtils.isNullOrEmpty(user_name) || page == 0 || rows == 0) {

            return ZhongkaiResult.build(400, "数据不完整");
        }

        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
        detachedCriteria.add(Restrictions.like("userName","%"+user_name+"%")); //增加条件
/*        detachedCriteria.add(Restrictions.eq("unitUuid", unit_uuid)); //增加条件
/*        detachedCriteria.add(Restrictions.eq("unitUuid", unit_uuid)); //增加条件
        detachedCriteria.addOrder(Order.desc("solveTime")); //根据传入的字段进行降序排序*/
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);


        List<SetUnit> list = pageBean.getRows();
        List<BigDateBean> bigDateBeans = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        BigUnitBean bigUnitBean; //设备实时数据对象

        //     System.out.println(rows1.size());
        String uuid;
        for (SetUnit setUnit : list) {

   /*         if (setUnit == null){
                pageBean.setRows(bigDateBeans);
                return ZhongkaiResult.ok(pageBean);
            }*/
            BigDateBean bigDateBean = new BigDateBean();

            uuid = setUnit.getSetUuid();
            String json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid); //查询缓存


            if (!StringUtils.isNullOrEmpty(json)) {


                bigUnitBean = mapper.readValue(json, BigUnitBean.class);


                //  System.out.println(b+"6666666");


                bigDateBean.setState(String.valueOf(setUnit.getSetStatus()));//设备状态 从redis中获取
                bigDateBean.setUser_name(setUnit.getUserName());//用户姓名 设备表中获取

                bigDateBean.setUnit_ip(setUnit.getSetIp());//设备ip地址 设备表中获取

                bigDateBean.setSignal(bigUnitBean.getSignal());//信号强度 从redis中获取

                bigDateBean.setPower(bigUnitBean.getPower()); //实时电压

                bigDateBean.setForce(bigUnitBean.getForce()); //实时电量

                bigDateBean.setPower_all(bigUnitBean.getPower_all());//总耗电量 设备表中获取

                bigDateBean.setUser_t(bigUnitBean.getUser_t());//设备设定温度 从redis中获取

                bigDateBean.setAddress_all(setUnit.getAppAddressAll());//设备完整地址 设备表中获取

                bigDateBean.setUnit_uuid(uuid);//设备uuid  设备表中获取

                bigDateBean.setWarning(bigUnitBean.getWarning()); //是否报警

                bigDateBean.setTrusteeship(setUnit.getTrusteeship()); //是否托管

                bigDateBean.setRepair(String.valueOf(setUnit.getRepair())); //是否维修

                bigDateBean.setUser_uuid(setUnit.getUserUuid());

                bigDateBean.setSetAlias(setUnit.getSetAlias());
            } else {

                // deviceOperationService.deviceDown2(uuid); //设备下线

                bigDateBean.setState("100");
                bigDateBean.setUser_name(setUnit.getUserName());//用户姓名 设备表中获取

                bigDateBean.setUnit_ip(setUnit.getSetIp());//设备ip地址 设备表中获取

                bigDateBean.setPower_all(setUnit.getBattery().toString());//总耗电量 设备表中获取

                bigDateBean.setAddress_all(setUnit.getAppAddressAll());//设备完整地址 设备表中获取

                bigDateBean.setUnit_uuid(uuid);//设备uuid  设备表中获取

                bigDateBean.setWarning(String.valueOf(setUnit.getWarning()));

                bigDateBean.setTrusteeship(setUnit.getTrusteeship()); //是否托管

                bigDateBean.setRepair(String.valueOf(setUnit.getRepair())); //是否维修
                bigDateBean.setUser_uuid(setUnit.getUserUuid());
                bigDateBean.setSetAlias(setUnit.getSetAlias());
            }


            bigDateBeans.add(bigDateBean);

            bigDateBean = null;

        }

        pageBean.setRows(bigDateBeans);

        return ZhongkaiResult.ok(pageBean);
    }


}
